package com.gupt.reggie.service.impl;/*
@author name
@data 2023/4/19-16:25
*/


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gupt.reggie.common.CustomException;
import com.gupt.reggie.entity.Category;
import com.gupt.reggie.entity.Dish;
import com.gupt.reggie.entity.Setmeal;
import com.gupt.reggie.mapper.CategoryMapper;
import com.gupt.reggie.service.CategoryService;
import com.gupt.reggie.service.DishService;
import com.gupt.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService{

    @Autowired
    DishService dishService;   //菜品

    @Autowired
    SetmealService setmealService;  //套餐

    /**
     * 根据id删除分类，需校验关联
     * @param id
     */
    @Override
    public void removeById(Long id) {

        //调用数据库查询 某菜品是否有该类型
        LambdaQueryWrapper<Dish> dishLambda = new LambdaQueryWrapper();
        dishLambda.eq(Dish::getCategoryId,id);
        int count1= dishService.count(dishLambda);

        //查询当前分类是否关联了菜品，若关联了，则抛出异常
        if(count1 > 0){
            //关联了，则抛出异常
            throw new CustomException("该分类关联了菜品，无法删除");  //为什么不 new RuntimeException("xxx")？？？
        }

        LambdaQueryWrapper<Setmeal> setMealLambda = new LambdaQueryWrapper();
        setMealLambda.eq(Setmeal::getCategoryId,id);
        int count2 = setmealService.count(setMealLambda);
        //查询当前分类是否关联了套餐，若关联了，则抛出异常;
        if(count2 > 0){
            //关联了，则抛出异常
            throw new CustomException("该分类关联了套餐，无法删除");
        }
        //正常删除
        super.removeById(id);   //super: 调用父类同名的方法removeById（）
    }
}
